<template>
  <el-dialog class="edit-box" :title="dialog.title" :visible.sync="dialog.visible" append-to-body top="5vh"
             width="570px">
    <el-form class="editInfo" ref="editInfo" :inline="true" :model="editInfo.data" :rules="editInfo.rules" size="small"
             label-width="80px">
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="editInfo.data.deptName" placeholder="请输入部门名称" style="width: 168px;"></el-input>
      </el-form-item>
      <template v-if="!editInfo.id || editInfo.data.parentId !== ''"></template>
      <el-form-item label="部门排序" prop="orderNum">
        <el-input-number v-model.number="editInfo.data.orderNum" :min="0" :max="999" controls-position="right"
                         style="width: 168px;"/>
      </el-form-item>
      <el-form-item label="负责人" prop="chargeUserId">
        <el-select v-model="editInfo.data.chargeUserId" filterable placeholder="请选择负责人" style="width: 168px;">
          <el-option label="请选择" value=""></el-option>
          <el-option v-for="(item, index) in leaderList" :key="`${item.nickName}${index}`" :label="item.nickName"
                     :value="item.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="助理" prop="assistantUserId">
        <el-select v-model="editInfo.data.assistantUserId" filterable placeholder="请选择助理" style="width: 168px;">
          <el-option label="请选择" value=""></el-option>
          <el-option v-for="(item, index) in assistantList" :key="`${item.nickName}${index}`" :label="item.nickName"
                     :value="item.userId"></el-option>
        </el-select>
      </el-form-item>
      <!--<el-form-item label="是否启用" prop="status" style="width: 380px;">
        <el-switch
          v-model="editInfo.data.status"
          active-value="0"
          inactive-value="1"
        ></el-switch>
      </el-form-item>-->
      <el-form-item  label="上级部门" prop="parentId" v-if="editInfo.data.parentId !== '0'" style="margin-bottom: 10px;">
        <tree-select v-model="editInfo.data.parentId" :options="departmentAllListData" :normalizer="treeSelectProps"
                     placeholder="选择上级部门"
                     style="width: 430px"/>
      </el-form-item>

      <!-- <el-form-item  label="工资审核" prop="salaryAuditDeptId" v-if="editInfo.data.salaryAuditDeptId !== '0'" style="margin-bottom: 10px;">
        <tree-select v-model="editInfo.data.salaryAuditDeptId" :options="departmentAllListDataGZ" :normalizer="treeSelectProps"
                     placeholder="选择工资审核部门"
                     style="width: 430px"/>
      </el-form-item> -->

       <el-form-item  label="工资审核" prop="salaryAuditDeptId"  style="margin-bottom: 10px;">
        <tree-select v-model="editInfo.data.salaryAuditDeptId" :options="departmentAllListDataGZ" :normalizer="treeSelectProps"
                     placeholder="选择工资审核部门"
                     style="width: 430px"/>
      </el-form-item>

       <el-form-item  label="开票审核" prop="invoiceAuditDeptId"  style="margin-bottom: 10px;">
        <tree-select v-model="editInfo.data.invoiceAuditDeptId" :options="departmentAllListDataGZ" :normalizer="treeSelectProps"
                     placeholder="选择开票审核部门"
                     style="width: 430px"/>
      </el-form-item>


    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialog.visible = false">取消</el-button>
      <el-button type="primary" @click="handleEditSubmit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { debounce } from 'lodash'
  import { createDepartmentAPI, updateDepartmentAPI, getDepartmentLeaderList } from '@/api/system/department'
  import TreeSelect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    name: 'DepartmentEdit',
    mixins: [],
    components: {
      TreeSelect
    },
    data() {
      return {
        dialog: {
          status: 'create',
          visible: false, // 是否显示
          title: '添加'
        },
        formParams: { // 编辑需要的参数
          deptName: undefined,
          orderNum: undefined,
          chargeUserId: undefined,
          assistantUserId: undefined,
          status: '0',
          parentId: undefined,
          salaryAuditDeptId: undefined,
          invoiceAuditDeptId: undefined

        },
        editInfo: { // 编辑表单
          id: undefined,
          data: {
            ...this.formParams
          },
          rules: {
            deptName: [
              { required: true, message: '部门名称不能为空', trigger: 'blur' }
            ],
            orderNum: [
              { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
            ],
            parentId: [
              { required: true, message: '上级部门不能为空', trigger: 'blur' }
            ]/*,
            salaryAuditDeptId: [
              { required: true, message: '工资审核部门不能为空', trigger: 'blur' }
            ]*/
          },
          disabled: false // 处理编辑，某些项禁止编辑
        },
        treeSelectProps(node) {
          return {
            id: node.id,
            label: node.label,
            children: node.children
          }
        },
        departmentAllListData: [],
        departmentAllListDataKP:[], //开票审核部门列表
        departmentAllListDataGZ:[],
        leaderList: [], // 负责人列表
        assistantList: [], // 助理列表
        detailInfo: null
      }
    },
    props: {
      visible: {
        type: [Boolean],
        required: true,
        default: false
      },
      detailData: {
        type: Object,
        default() {
          return null
        }
      }
    },
    computed: {
      ...mapGetters('department', [
        'departmentList'
      ])
    },
    methods: {
      handleEditSubmit: debounce(function() { // 编辑，提交，防抖
        this.$refs['editInfo'].validate((valid) => {
          if (valid) {
            if (this.editInfo.id) {
              this.updateData()
            } else {
              this.createData()
            }
          }
        })
      }, 300),
      async createData() { // 添加－请求数据
        try {
          let { deptName } = this.editInfo.data
          let response = await createDepartmentAPI({
            ...this.editInfo.data,
            ...{
              deptName: deptName.trim()
            }
          })
          let result = response
          if (+result.code === 200) {
            this.dialog.visible = false
            this.$notify({
              title: '成功',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
            this.$emit('create')
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '添加失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '添加失败！'
          })
        }
      },
      async updateData() { // 修改－请求数据
        try {
          let { deptName } = this.editInfo.data
          let response = await updateDepartmentAPI({
            ...this.editInfo.data,
            ...{
              deptId: this.editInfo.id,
              deptName: deptName.trim()
            }
          })
          let result = response
          if (+result.code === 200) {
            this.dialog.visible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.$emit('update')
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '编辑失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '编辑失败！'
          })
        }
      },
      async getDepartmentLeaderListData() { // 查询部门负责人
        try {
          let response = await getDepartmentLeaderList({ type: 'SYS_CHARGE' })
          let result = response
          if (+result.code === 200) {
            this.leaderList = result.data || []
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '获取列表失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '获取列表失败!'
          })
        }
      },
      async getDepartmentAssistantListData() { // 查询部门助理
        try {
          let response = await getDepartmentLeaderList({ type: 'SYS_ASSISTANT' })
          let result = response
          if (+result.code === 200) {
            this.assistantList = result.data || []
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '获取列表失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '获取列表失败!'
          })
        }
      },
      async getDepartmentAllListData() { // 获取所有数据
        try {
          await this.$store.dispatch('department/GetDepartmentList', {
            request: true
          })
           this.departmentAllListDataKP = this.departmentAllListData.slice().concat([{id:"0",label:'流程结束'}]);
          this.departmentAllListDataGZ = this.departmentAllListData.slice().concat([{id:"0",label:'流程结束'}]);
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message
          })
        }
      },
      async resetEditData(data = null) { // 重置编辑表单
        this.dialog.status = data ? 'update' : 'create'
        this.dialog.title = data ? '编辑' : '添加'
        // this.dialog.visible = true
        this.editInfo.id = undefined
        this.editInfo.disabled = false
        this.editInfo.data = {
          ...this.formParams
        }
        if (data) { // 编辑
          // this.editInfo.id = data.uuid
          this.editInfo.id = data.deptId
          Object.keys(this.formParams).forEach((item) => {
            this.editInfo.data[item] = data[item]
          })
          this.editInfo.disabled = true
        }
      },
      async initEditDialog(data = null) { // 编辑－显示弹出框
        await this.resetEditData(data)
        this.getDepartmentAllListData()
        this.getDepartmentLeaderListData()
        this.getDepartmentAssistantListData()
        this.$nextTick(() => {
          this.$refs['editInfo'].clearValidate()
        })
      }
    },
    watch: {
      visible(newVal, oldVal) {
        if (newVal !== this.dialog.visible) {
          this.dialog.visible = newVal
          if (newVal) {
            this.initEditDialog(this.detailData)
          }
        }
      },
      'dialog.visible'(newVal, oldVal) {
        this.$emit('update:visible', newVal)
      },
      'departmentList': {
        handler: function(newVal, oldVal) {
          this.departmentAllListData = newVal
          /* this.departmentAllListData = []
          let rootData = { id: '0', label: '顶级类目', children: [] }
          rootData.children = newVal || []
          this.departmentAllListData.push(rootData) */

        // console.log(11111);

        },
        deep: true,
        immediate: true
      }
    },
    created() {
    },
    mounted() {
    }
  }
</script>

<style lang="scss" scoped>
  .editInfo {
    margin-right: 0;
  }

  .el-cascader,
  .el-select {
    width: 100%;
  }
</style>
